package main

import (
	"database/sql"
	"log"

	_ "github.com/lib/pq" // postgres driver
)

type dbContext struct {
	db *sql.DB
}

var DBConn *dbContext

func DBInit() {
	errstr := ""
	DBConn, errstr = connectDB("postgres", "port=5432 user=postgres password=postgres dbname=ihos sslmode=disable")
	if len(errstr) > 0 {
		log.Fatal("connect Database error:" + errstr)
	}
}

// ConnectDB connect specify database
func connectDB(driverName string, dbName string) (c *dbContext, errorMessage string) {
	db, err := sql.Open(driverName, dbName)
	if err != nil {
		return nil, err.Error()
	}
	if err = db.Ping(); err != nil {
		return nil, err.Error()
	}
	return &dbContext{db}, ""
}
